﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AMail.Modules.Folders.Interfaces;
using AMail.Common.Interfaces.Data;
using System.Diagnostics;
using Elentok.Common.Wpf;
using Elentok.Common.Wpf.Helpers;
using Elentok.Common.Wpf.Controls;

namespace AMail.Modules.Folders
{
  /// <summary>
  /// Interaction logic for FoldersView.xaml
  /// </summary>
  public partial class FoldersView : UserControl
  {
    private TreeViewDragDropManager<IFolderViewModel> dragDropManager;

    public FoldersView(IFoldersTreeViewModel viewModel)
    {
      InitializeComponent();

      this.DataContext = viewModel;
      this.dragDropManager = new TreeViewDragDropManager<IFolderViewModel>(this.foldersTree);
      this.dragDropManager.Drop = viewModel.Drop;
      this.dragDropManager.CanDrop = viewModel.CanDrop;
      this.dragDropManager.CanDrag = viewModel.CanDrag;

      this.InputBindings.Add(new KeyBinding(viewModel.CreateSubfolderCommand, new KeyGesture(Key.Insert)));
      this.InputBindings.Add(new KeyBinding(viewModel.DeleteFolderCommand, new KeyGesture(Key.Delete)));
      this.InputBindings.Add(new KeyBinding(viewModel.RenameFolderCommand, new KeyGesture(Key.F2)));
    }

    public IFoldersTreeViewModel ViewModel
    {
      get { return (IFoldersTreeViewModel)this.DataContext; }
    }

    private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseEventArgs e)
    {
      DependencyObject source = e.OriginalSource as DependencyObject;
      TreeViewItem item = source.FindAncestor<TreeViewItem>();
      if (item != null)
      {
        item.IsSelected = true;
        e.Handled = true;
      }
    }

    ///// <summary>
    ///// Focus the selected item after it's selected (otherwise selection gets messed up)
    ///// </summary>
    ///// <param name="sender"></param>
    ///// <param name="e"></param>
    //private void foldersTreeViewItem_Selected(object sender, RoutedEventArgs e)
    //{
    //  TreeViewItem item = e.OriginalSource as TreeViewItem;
    //  IFolderViewModel viewModel = null;
      
    //  if (item != null)
    //  {
    //    viewModel = (IFolderViewModel)item.DataContext;

    //    if (!item.IsFocused)
    //      item.Focus();
    //  }

    //  ViewModel.SetSelectedFolderCommand.Execute(viewModel);
    //}
    
  }
}
